﻿using NHibernate;
using NHibernate.Context;
using Ninject;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Wicresoft.EKA.MVCExtensions
{
    public class BaseController : Controller
    {
        public Dictionary<String, String> UserPreferences { get; private set; }
        public ICollection<String> Roles { get; private set; }

        [Inject]
        public IUserInfo UserInfo { get; set; }

        public String UserName
        {
            get
            {
                return User.Identity.Name;
            }
        }

        protected ISessionFactory SessionFactory
        {
            get
            {
                return MVCExtensions.SessionFactory;
            }
        }

        internal void OnBeforeAuthorize()
        {
            InitUserInfo();
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            InitUserInfo();
            base.OnActionExecuting(filterContext);
        }

        protected override void Dispose(bool disposing)
        {
            CurrentSessionContext.Unbind(SessionFactory).Close();
            ((IDisposable)UserInfo).Dispose();
            base.Dispose(disposing);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewBag.Roles = Roles;
            ViewBag.UserPreferences = UserPreferences;

            base.OnActionExecuted(filterContext);
        }

        private void InitUserInfo()
        {
            if (!MVCExtensions.IsDoneInThisRequest(HttpContext, MVCExtensions.UserInfoInitedKey))
            {
                ((IBase)UserInfo).UserIdentify = UserName;
                UserPreferences = UserInfo.GetUserPreferenceByUserIdentify(UserName);
                Roles = UserInfo.GetUserInRolesByUserIdentify(UserName);
                CurrentSessionContext.Bind(SessionFactory.OpenSession());
                MVCExtensions.SetDoneInThisRequest(HttpContext, MVCExtensions.UserInfoInitedKey);
            }
        }

    }
}
